package com.awcall.iot.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;

public class JwtUtils {

    private static final String KEY = "awcall-iot";
    private static byte[] base64KeyByte;
    private static String base64KeyString;

    static {
        try {
            base64KeyByte = Base64.getEncoder().encode(KEY.getBytes("utf-8"));
            base64KeyString = new String(base64KeyByte, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String sign(Integer id) {
        return Jwts.builder()
                .setExpiration(DateUtils.addDays(new Date(), 7))
                .setId(id.toString())
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS512, base64KeyString)
                .compact();
    }

    public static Claims parse(String jwt) {
        if (!Jwts.parser().isSigned(jwt)) {
            throw new IllegalArgumentException();
        }

        byte[] decodeKey = Base64.getDecoder().decode(base64KeyByte);
        return Jwts.parser()
                .setSigningKey(decodeKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) {
        String sign = sign(1);
        System.out.println(sign);
//        Claims parse = parse("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1MTM1NjM2MDQsImp0aSI6IjEiLCJpYXQiOjE1MTI5NTg4MDR9.hm7tcvfrSexkB3W2uus94zI2xnlqdS73z-y3zPRqxIM3dDa6PI6HTvImzuPQRVV6pPUod-GOHvXVDn4XANRD3A");
//        System.out.println(parse.getId());
        //eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1MTM1NjE0NDIsImp0aSI6IjEiLCJpYXQiOjE1MTI5NTY2NDJ9.oIkS1eABqdbL8VTcgthr75KfLrdnQ5M3ykjTGvi0xUN1ihK5tBB3ELyzYcB92k1GlUHc6meL7IUlNqNut0mT7g
        //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjkzMDI3MjA3NzMwNTQ3MDk3NywiZXhwaXJlZCI6MTUxMzU1OTUzMjY5M30.GHVXNFR01QCbOIUKWMKT_PUU5vD4GvbUWEhzGRMTvo4
    }

}
